package com.jumper.property.comparer.core.convert.impl;

import com.alibaba.fastjson.JSON;
import com.jumper.property.comparer.core.convert.PropertyConverter;
import com.jumper.property.comparer.core.annotations.convert.BooleanFormat;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * Boolean属性转换器
 */
@Slf4j
public class BooleanPropertyConverter implements PropertyConverter {

    @Override
    public Object convert(Object propertyValue, Field field) {
        if (propertyValue == null) {
            return null;
        }
        BooleanFormat booleanFormat = field.getAnnotation(BooleanFormat.class);
        if (booleanFormat == null) {
            return propertyValue;
        }
        try {
            return (Boolean) propertyValue ? booleanFormat.trueValue() : booleanFormat.falseValue();
        } catch (Exception e) {
            log.warn("Boolean格式转换异常:{}", JSON.toJSONString(propertyValue), e);
        }
        return propertyValue;
    }
}
